<template>
	<view class="container">
		<!-- 询价单基本信息 -->
		<view class="form-section">
			<view class="section-title">询价单基本信息</view>

			<!-- 截止时间 -->
			<view class="form-item">
				<view class="form-label">截止时间</view>
				<view class="time-picker" @click="this.$refs.datetimePicker.open()">
					<text class="time-value">{{ deadline || '请选择截止时间' }}</text>
					<text class="icon">▼</text>
				</view>
			</view>

			<!-- 时间选择器 -->
			<uv-datetime-picker ref="datetimePicker" v-model="dateValue" mode="datetime" :formatter="formatter"
				@confirm="dateConfirm">
			</uv-datetime-picker>
		</view>

		<!-- 商品列表 -->
		<view class="form-section">
			<view class="section-header">
				<view class="section-title">商品列表(最多5个)</view>
				<view class="section-subtitle">型号 | 品牌 | 需求数量 | 备注</view>
			</view>

			<view class="product-list">
				<view class="product-item" v-for="(product, index) in products" :key="index">
					<view class="product-header">
						<text class="product-index">商品{{ index + 1 }}</text>
						<text class="delete-product" v-if="products.length > 1" @click="deleteProduct(index)">
							删除
						</text>
					</view>

					<!-- 型号 -->
					<view class="form-item">
						<uv-input type="text" placeholder="输入型号" border="surround" v-model="product.model"
							:clearable="true"></uv-input>
					</view>

					<!-- 品牌、数量、备注 -->
					<view class="product-details">
						<!-- 品牌选择 -->
						<view class="detail-item">
							<view class="picker-display" @click="openBrandPicker(index)">
								{{ product.brandName || '选择品牌' }}
							</view>
							<uv-picker :ref="`brandPicker${index}`" :columns="brandList" keyName="name"
								@confirm="brandConfirm($event, index)"></uv-picker>
						</view>

						<!-- 需求数量 -->
						<view class="detail-item">
							<uv-input type="number" placeholder="数量" border="surround"
								v-model="product.quantity"></uv-input>
						</view>

						<!-- 备注 -->
						<view class="detail-item remark">
							<uv-input type="text" placeholder="备注" border="surround" v-model="product.note"></uv-input>
						</view>
					</view>
				</view>
			</view>

			<!-- 添加商品按钮 -->
			<view class="add-product-btn" @click="addProduct" v-if="products.length < 5">
				<text class="add-icon">+</text>
				<text class="add-text">添加商品</text>
			</view>

			<view class="max-tip" v-else>
				已添加5个商品，已达上限
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="action-buttons">
			<!-- <view class="action-btn draft" @click="saveDraft">保存询价单草稿</view> -->
			<view class="action-btn publish" @click="publishInquiry">确认发布</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				inquiryId: 0,
				deadline: '',
				brandList: [],
				products: [{
					model: '',
					brandId: '',
					brandName: '',
					quantity: '',
					note: ''
				}],
				dateValue: Number(new Date()),
			};
		},
		onLoad(option) {
			console.log(1111, option)
			if (option.id && option.id > 0) {
				this.inquiryId = option.id;
				this.loadData(option.id);
			}
			this.brandListApi();
		},
		methods: {
			loadData(id) {
				uni.$uv.http.get('/inquiry/inquiryDetail', {
					params: {
						inquiry_id: id
					},
				}).then(res => {
					if (res.res.code == 1) {
						const data = res.res.data;
						this.deadline = data.inquiry.deadline_formatted;
						this.products = data.products.map(item => ({
							...item,
							model: item.product_model,
							brandId: item.brand_id,
							brandName: item.brand_name,
							quantity: item.required_quantity,
						}));
						return;
					}
					this.$wanlshop.msg(res.res.msg, 3000, true, 'none');
				}).catch(error => {
					console.log('error', error)
					this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
				});
			},
			openBrandPicker(index) {
				this.$refs[`brandPicker${index}`][0].open()
			},
			// 时间选择确认
			dateConfirm(e) {
				if (e.value < new Date().getTime()) {
					this.$wanlshop.msg('选择的时间不能小于当前时间！');
					return;
				}
				this.deadline = this.$wanlshop.timeFormat(e.value, 'yyyy-mm-dd hh:MM');
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},

			// 获取品牌
			async brandListApi() {
				uni.showLoading({
					title: "加载中..."
				})
				const data = {
					show_all: false
				};
				// 请求数据
				await uni.request({
					url: '/wanlshop.product/brandList',
					data: data,
					success: res => {
						uni.hideLoading();
						this.brandList = [res.data];
					}
				});
			},

			// 品牌选择确认
			brandConfirm(e, index) {
				console.log('brandConfirm', e);
				const brandIndex = e.value[0];
				this.products[index].brandId = brandIndex.id;
				this.products[index].brandName = brandIndex.name;
				this.$forceUpdate();
			},

			// 添加商品
			addProduct() {
				if (this.products.length < 5) {
					this.products.push({
						model: '',
						brandId: '',
						brandName: '',
						quantity: '',
						note: ''
					});
				}
			},

			// 删除商品
			deleteProduct(index) {
				if (this.products.length > 1) {
					this.products.splice(index, 1);
				}
			},

			// 保存草稿
			saveDraft() {
				if (this.validateForm()) {
					const updatedProducts = this.products.map(item => ({
						model: item.model,
						brand_id: item.brandId,
						required_quantity: item.quantity,
						note: item.note
					}));
					if (this.inquiryId === 0) {
						this.createInquiry(this.deadline, 'draft', updatedProducts);
					} else {
						this.editInquiry(this.deadline, 'draft', updatedProducts);
					}
				}
			},

			// 发布询价单
			publishInquiry() {
				if (this.validateForm()) {
					uni.showModal({
						title: '确认发布',
						content: '确定要发布这个询价单吗？',
						success: (res) => {
							if (res.confirm) {
								const updatedProducts = this.products.map(item => ({
									model: item.model,
									brand_id: item.brandId,
									required_quantity: item.quantity,
									note: item.note
								}));
								this.createInquiry(this.deadline, 'published', updatedProducts);
							}
						}
					});
				}
			},

			// 提交
			async createInquiry(deadline, status, products) {
				uni.$uv.http.post('/inquiry/createInquiry', {
					deadline,
					status,
					products,
				}).then(res => {
					if (res.res.code == 1) {
						this.$wanlshop.msg(res.res.msg);
						// 发布成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						this.$wanlshop.msg(res.res.msg, 3000, true, 'none');
					}
				}).catch(error => {
					this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
				});
			},

			// 修改
			async editInquiry(deadline, status, products) {
				uni.$uv.http.post('/inquiry/editInquiry', {
					inquiry_id: this.inquiryId,
					deadline,
					status,
					products,
				}).then(res => {
					if (res.res.code == 1) {
						this.$wanlshop.msg(res.res.msg);
						// 发布成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						this.$wanlshop.msg(res.res.msg, 3000, true, 'none');
					}
				}).catch(error => {
					this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
				});
			},

			// 表单验证
			validateForm() {
				if (!this.deadline) {
					uni.showToast({
						title: '请选择截止时间',
						icon: 'none'
					});
					return false;
				}

				for (let i = 0; i < this.products.length; i++) {
					const product = this.products[i];
					if (!product.model) {
						uni.showToast({
							title: `请填写商品${i + 1}的型号`,
							icon: 'none'
						});
						return false;
					}

					if (!product.quantity || product.quantity <= 0) {
						uni.showToast({
							title: `请填写商品${i + 1}的有效数量`,
							icon: 'none'
						});
						return false;
					}
				}

				return true;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 120rpx;
	}

	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.section-header {
			margin-bottom: 30rpx;
		}

		.section-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 8rpx;
		}

		.section-subtitle {
			font-size: 24rpx;
			color: #999;
		}
	}

	.form-item {
		margin-bottom: 30rpx;

		.form-label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 16rpx;
			font-weight: 500;
		}

		.time-picker {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 24rpx;
			border: 1rpx solid #e0e0e0;
			border-radius: 8rpx;
			background-color: #fff;

			.time-value {
				font-size: 28rpx;
				color: #333;
			}

			.icon {
				font-size: 24rpx;
				color: #999;
			}
		}

		.form-input {
			width: 100%;
			padding: 20rpx 24rpx;
			border: 1rpx solid #e0e0e0;
			border-radius: 8rpx;
			font-size: 28rpx;
			box-sizing: border-box;
		}
	}

	.product-list {
		.product-item {
			margin-bottom: 40rpx;
			padding-bottom: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
				margin-bottom: 0;
			}
		}

		.product-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.product-index {
				font-size: 26rpx;
				color: #333;
				font-weight: 500;
			}

			.delete-product {
				font-size: 24rpx;
				color: #fe6600;
			}
		}

		.product-details {
			display: flex;
			justify-content: space-between;

			.detail-item {
				flex: 1;
				margin-right: 16rpx;

				&:last-child {
					margin-right: 0;
				}

				&.remark {
					flex: 2;
				}

				.picker-display {
					padding: 18rpx 16rpx;
					border: 1rpx solid #e0e0e0;
					border-radius: 8rpx;
					font-size: 26rpx;
					color: #333;
					background-color: #fff;
					text-align: center;
				}

				.quantity-input,
				.remark-input {
					width: 100%;
					border: 1rpx solid #e0e0e0;
					border-radius: 8rpx;
					font-size: 28rpx;
					box-sizing: border-box;
				}
			}
		}
	}

	.add-product-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 24rpx;
		border: 1rpx dashed #fe6600;
		border-radius: 8rpx;
		color: #fe6600;
		margin-top: 20rpx;

		.add-icon {
			font-size: 32rpx;
			margin-right: 12rpx;
		}

		.add-text {
			font-size: 28rpx;
		}
	}

	.max-tip {
		text-align: center;
		font-size: 26rpx;
		color: #999;
		margin-top: 20rpx;
	}

	.action-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);

		.action-btn {
			flex: 1;
			padding: 24rpx;
			text-align: center;
			border-radius: 8rpx;
			font-size: 30rpx;
			font-weight: 500;
			margin: 0 10rpx;

			&.draft {
				background-color: #fff;
				color: #fe6600;
				border: 1rpx solid #fe6600;
			}

			&.publish {
				background-color: #fe6600;
				color: #fff;
			}
		}
	}

	.placeholder {
		color: #ccc;
		font-size: 28rpx;
	}
</style>